const lodash = require('lodash')
const loginFns = require("../common/login")
import { pageFns } from '../utils/pageHelper'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleDao } from '@/dao/articleDao'

const SELECTORS = { "IMAGE_TAB": [".upload-container .header .tab:nth-child(2)"], "IMAGE_INPUT": [".upload-area .drag-over input[type=\"file\"]"], "UPLOADING": [".img-list .img-container .uploading"], "TITLE_INPUT": [".post-page .content .titleInput input[type=\"text\"]"], "CONTENT_INPUT": ["#post-textarea"], "COMFIRM_BTN": [".post-page .submit .submit button:nth-child(1)"] }

// 发布
async function startPost(page, article, images, selectors) {
    let res = await pageFns.deepRetry(selectors.IMAGE_TAB, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
    }, { page: page, timeout: 10 * 1000, wait: 5 * 1000 })
    if (res.err) {
        return res
    }
    res = await pageFns.deepRetry(selectors.IMAGE_INPUT, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await pageFns.fileUpload({ page, element: selector, files: images })
    }, { page: page, wait: 5 * 1000 })
    if (res.err) {
        return res
    }
    res = await pageFns.deepRetry(selectors.UPLOADING, page, async (selector, page) => {
        await pageFns.waitDisappear(page, selector)
    })
    if (res.err) {
        return res
    }
    //2. 获取原始文章并填入标题
    res = await pageFns.deepRetry(selectors.TITLE_INPUT, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.type(selector, funcFns.truncateText(article.title, 40))
    }, { page: page, wait: 5 * 1000 })
    if (res.err) {
        return res
    }
    res = await pageFns.deepRetry(selectors.CONTENT_INPUT, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.type(selector, funcFns.truncateText(article.content, 1000))
    }, { page: page, wait: 5 * 1000 })
    if (res.err) {
        return res
    }
    //3. 提交按钮
    res = await pageFns.deepRetry(selectors.COMFIRM_BTN, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
        await pageFns.waitDisappear(page, selector)
    }, { page: page, wait: 5 * 1000 })
    if (res.err) {
        return res
    }
    return { data: "发布成功" }
}

const LOGINS = {
    LOGINBTNS: [],
    USERNAMES: ['input[placeholder="手机号"]'],
    NEXTSTEPS: ['div::-p-text("发送验证码")'],
    PASSWORDS: [],
    AGREEMENTBTNS: [],
    COMFIRMBTNS: ["button .btn-content"],
    UNLOGINFLAGS: ['.login-container']
}

async function goPost(page, task, article, rule) {
    let selectors = JSON.parse(rule.codeRule)
    if (lodash.isEmpty(selectors)) {
        return { err: "找不到发布规则:" + task.id }
    }
    let images = funcFns.getImages(ArticleDao.folderPath(article))
    if (lodash.isEmpty(images)) {
        return { data: "找不到发布的图片" }
    }
    let res = await loginFns.checkLogin(page, task, LOGINS)
    if (res.err) {
        console.log("goPost.checkLogin", res)
        return res
    }
    // 收集图片
    try {
        let dataFields = JSON.parse(task.dataFields)
        if (lodash.isEmpty(dataFields)) {
            return { err: "没有指定的数据" }
        }
        let aiResult = JSON.parse(article.aiResult)
        let langObj = JSON.parse(aiResult[task.lang])
        let contents = {}
        for (let dataField of dataFields) {
            contents[dataField] = lodash.trim(langObj[dataField], '"')
        }
        console.log("test", contents, langObj["title"], images)
        return await startPost(page, contents, images, selectors)
    } catch (err) {
        console.log("goPost", err, article)
        return { err: err }
    }
}

export { goPost }